package mango.service.db.task;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import mango.Mango;
import mango.functions.FuncString;

public class DBTaskProceser {
    private static DBTaskProceser instance;

    private int maxHandlerSize = 10;

    private List<DBTaskHandler> handlers;

    private DBTaskProceser() {
        this.handlers = new LinkedList<DBTaskHandler>();
        if(!FuncString.isBlank(Mango.getProperty(Mango.MAX_DB_HANDLER))) {
            this.maxHandlerSize = Integer.parseInt(Mango.getProperty(Mango.MAX_DB_HANDLER));
        }
    }

    public static DBTaskProceser getInstance() {
        if (instance == null) {
            instance = new DBTaskProceser();
        }
        return instance;
    }

    public boolean distribute(DBTaskProcessable task) {
        if (handlers.size() > maxHandlerSize) {
            for (Iterator<DBTaskHandler> iter = handlers.iterator(); iter.hasNext();) {
                DBTaskHandler handler = iter.next();
                handler.postClose();
                iter.remove();
            }
        }
        else if(handlers.size() < maxHandlerSize){
            createHandler();
        }
        for (Iterator<DBTaskHandler> iter = handlers.iterator(); iter.hasNext();) {
            if(iter.next().addTask(task)) {
                return true;
            }
        }
        return false;
    }

    private void createHandler() {
        DBTaskHandler handler = new DBTaskHandler();
        handlers.add(handler);
    }
}
